<template>
  <div class="sanstyle">
    <!--左边 B-->
    <div>
      <div class="ssl" style="position: relative">
        <!--标题 B-->
        <div class="sstitle">
          <div class="twz">
            <span class="dwz">设备选择</span>
            <br/>
            <span class="xwz">Equipment selection</span>
          </div>
        </div>
        <!--标题 E-->

        <!--监控列表 B-->
        <div class="jklb">
          <div class="ssk" style="margin-top: .15rem;">
            <input type="text" placeholder="设备名称/区域查询" v-model="keyword"/>
            <img style="cursor: pointer" src="/static/images/ss.png" alt="">
          </div>

          <div class="lbbox" v-for="(item,index) in list" :key="index"
               :style="item.color?'color:#2efff2':'color:#ffffff'"
               @click="singlepreview(item),backPaly(item),qiehuansxt(item)">
            <div><span>{{item.name}}</span></div>
            <!--<span class="icon iconfont icon-huifang"></span>-->
            <div><span class="icon iconfont icon-yulan"></span></div>
          </div>

        </div>
        <!--监控列表 E-->
      </div>
    </div>
    <!--左边 E-->
    <!--中间 B-->
    <div>
      <div id="map" style="width: 100%;height: 100%;"></div>
    </div>
    <!--中间 E-->
    <!--右边 B-->
    <div>
      <div class="ssls">
        <!--标题 B-->
        <div class="sstitles">
          <div class="twzs">
            <span class="dwz">视频直播</span>
            <br/>
            <span class="xwz">Video footage</span>
          </div>
        </div>
        <!--标题 E-->

        <!--视频画面 B-->
        <div class="zhibo" id="playWnd"></div>
        <!--视频画面 E-->

        <!--标题 B-->
        <div class="sstitles" style="margin-top: .1rem;">
          <div class="twzs">
            <span class="dwz">视频回放</span>
            <br/>
            <span class="xwz">Video playback</span>
          </div>
        </div>
        <!--标题 E-->
        <!--视频回放 B-->
        <div class="zhibo" id="backWnd"></div>
        <!--视频回放 E-->
      </div>
    </div>
    <!--右边 E-->

    <!--未装插件提示B-->
    <div class="plugWeb" v-if="isplug">
      <div style="text-align: center">
        <img src="/static/images/kongjian.png" alt="">
      </div>
      <div style="color: #5a5a65;text-align: center;">
        <span style="font-size: .24rem;line-height: .6rem;">控件未安装或加载失败</span>
        <br>
        <span style="font-size: .16rem;line-height: .4rem;">若未安装成功，请下载安装控件</span>
        <br>
        <span style="font-size: .16rem;">若已安装控件，请先尝试重启浏览器重试当前操作；若问题仍然存在，建议检查网络或重新安装控件。</span>
      </div>

      <div style="text-align: center;margin-top: .3rem;font-size: .2rem;">
        <a href="http://nxluoshan.baohuqu.net:1087/api/res/VideoWebPlugin.exe"
           target="_self"><span
          class="el-icon-download"></span>下载浏览器控件</a>
      </div>
    </div>
    <!--未装插件提示E-->

  </div>
</template>

<script>
  import * as echarts from 'echarts'
  import api from '../utils/api'
  import http from '../utils/http'


  export default {
    name: "shipinjiankong",
    data() {
      return {
        keyword: "",
        list: [],
        oWebControl: null,
        oBacControl: null,
        isplug: false,
        areaId: "",
        port: "",
        host: "",
        appKey: "",
        appSecret: "",
        isplug: false
      }
    },
    created() {
      this.areaId = window.sessionStorage.getItem('areaId');
      this.getoai();
      this.getlist();
    },
    mounted() {
      this.map();
      let _that = this;
      setTimeout(function () {
        _that.initPlugin();
        _that.initbackWnd();
        setTimeout(function () {
          _that.singlepreview(_that.list[0]);
          _that.backPaly(_that.list[0]);
        }, 2000)
      }, 1000)
    },
    methods: {
      getoai() {
        let vm = this;
        (async function f() {
          let res = await http.get(api.getOpenApiInfo + vm.areaId)
          if (res.data.code == '200') {
            let obj = res.data.data;
            vm.port = obj.port;
            vm.host = obj.host;
            vm.appKey = obj.appKey
            vm.appSecret = obj.appSecret
          }
        })()
      },
      getlist() {
        let vm = this;
        (async function f() {
          let res = await http.get(api.visualVideoList + vm.areaId)
          if (res.data.code == '200') {
            let arr = [];
            res.data.data.forEach((i, x) => {
              let z = {};
              if (x == 0) {
                z = {
                  name: i.name,
                  indexCode: i.indexCode,
                  color: true,
                  lat: i.lat,
                  lon: i.lon
                }
              } else {
                z = {
                  name: i.name,
                  indexCode: i.indexCode,
                  color: false,
                  lat: i.lat,
                  lon: i.lon
                }
              }
              arr.push(z)
            })
            vm.list = arr;
          }
        })()
      },
      qiehuansxt(item) {
        this.list.forEach(y => {
          y.color = false
        })
        item.color = true;
      },
      singlepreview(data) {
        var cameraIndexCode = data.indexCode;     //获取输入的监控点编号值，必填
        var streamMode = 0;                                     //主子码流标识：0-主码流，1-子码流
        var transMode = 1;                                      //传输协议：0-UDP，1-TCP
        var gpuMode = 0;                                        //是否启用GPU硬解，0-不启用，1-启用
        var wndId = -1;                                         //播放窗口序号（在2x2以上布局下可指定播放窗口）
        cameraIndexCode = cameraIndexCode.replace(/(^\s*)/g, "");
        cameraIndexCode = cameraIndexCode.replace(/(\s*$)/g, "");
        this.oWebControl.JS_RequestInterface({
          funcName: "startPreview",
          argument: JSON.stringify({
            cameraIndexCode: cameraIndexCode,                //监控点编号
            streamMode: streamMode,                         //主子码流标识
            transMode: transMode,                           //传输协议
            gpuMode: gpuMode,                               //是否开启GPU硬解
            wndId: wndId                                     //可指定播放窗口
          })
        })
      },
      initPlugin() {
        //声明公用变量
        var that = this;
        let initCount = 0;
        let pubKey = '';
        let iWidth = $("#playWnd").width();
        let iHeight = $("#playWnd").height();
        that.oWebControl = new WebControl({ // 创建 WebControl 实例
          szPluginContainer: "playWnd", // 指定 DIV 窗口标识
          iServicePortStart: 15900, // 指定起止端口号，建议使用该值
          iServicePortEnd: 15909,
          // 用于 IE10 使用 ActiveX 的 clsid
          szClassId: "23BF3B0A-2C56-4D97-9C03-0CB103AA8F11",
          cbConnectSuccess: function () {
            // 创建 WebControl 实例成功
            that.oWebControl.JS_StartService("window", {         // WebControl实例创建成功后需要启动服务
              dllPath: "./VideoPluginConnect.dll"         // 值"./VideoPluginConnect.dll"写死
            }).then(function () {                           // 启动插件服务成功
              that.oWebControl.JS_SetWindowControlCallback({   // 设置消息回调
                cbIntegrationCallBack: cbIntegrationCallBack
              });
              that.oWebControl.JS_CreateWnd("playWnd", iWidth, iHeight).then(function () { //JS_CreateWnd创建视频播放窗口，宽高可设定
                init();  // 创建播放实例成功后初始化
              });
            }, function () { // 启动插件服务失败
              that.isplug = true;
            });
          },
          cbConnectError: function () {
            // 创建 WebControl 实例失败

          },
          cbConnectClose: function (bNormalClose) {
            that.oWebControl = null;
            // 插件使用过程中发生的断开与插件服务连接的回调
            // bNormalClose = false 时表示异常断开
            // bNormalClose = true 时表示正常断开
          }
        })

        function cbIntegrationCallBack(oData) {
          // console.log(JSON.stringify(oData.responseMsg));
        }

        function init() {
          getPubKey(function () {
            ////////////////////////////////// 请自行修改以下变量值	////////////////////////////////////
            var appkey = that.appKey;                //综合安防管理平台提供的appkey，必填
            var secret = setEncrypt(that.appSecret);   //综合安防管理平台提供的secret，必填
            var ip = that.host;                          //综合安防管理平台IP地址，必填
            var playMode = 0;                                  //初始播放模式：0-预览，1-回放
            var port = that.port;                                      //综合安防管理平台端口，若启用HTTPS协议，默认443
            var snapDir = "D:\\SnapDir";                       //抓图存储路径
            var videoDir = "D:\\VideoDir";                     //紧急录像或录像剪辑存储路径
            var layout = "1x1";                                //playMode指定模式的布局
            var enableHTTPS = 1;                               //是否启用HTTPS协议与综合安防管理平台交互，这里总是填1
            var encryptedFields = 'secret';					   //加密字段，默认加密领域为secret
            var showToolbar = 1;                               //是否显示工具栏，0-不显示，非0-显示
            var showSmart = 1;                                 //是否显示智能信息（如配置移动侦测后画面上的线框），0-不显示，非0-显示
            var buttonIDs = "0,16,256,257,258,259,260,512,513,514,515,516,517,768,769";  //自定义工具条按钮
            ////////////////////////////////// 请自行修改以上变量值	////////////////////////////////////

            that.oWebControl.JS_RequestInterface({
              funcName: "init",
              argument: JSON.stringify({
                appkey: appkey,                            //API网关提供的appkey
                secret: secret,                            //API网关提供的secret
                ip: ip,                                    //API网关IP地址
                playMode: playMode,                        //播放模式（决定显示预览还是回放界面）
                port: port,                                //端口
                snapDir: snapDir,                          //抓图存储路径
                videoDir: videoDir,                        //紧急录像或录像剪辑存储路径
                layout: layout,                            //布局
                enableHTTPS: enableHTTPS,                  //是否启用HTTPS协议
                encryptedFields: encryptedFields,          //加密字段
                showToolbar: showToolbar,                  //是否显示工具栏
                showSmart: showSmart,                      //是否显示智能信息
                buttonIDs: buttonIDs                       //自定义工具条按钮
              })
            }).then(function (oData) {
              that.oWebControl.JS_Resize(iWidth, iHeight);  // 初始化后resize一次，规避firefox下首次显示窗口后插件窗口未与DIV窗口重合问题
            });
          });
        }

        function getPubKey(callback) {
          that.oWebControl.JS_RequestInterface({
            funcName: "getRSAPubKey",
            argument: JSON.stringify({
              keyLength: 1024
            })
          }).then(function (oData) {
            console.log(oData);
            if (oData.responseMsg.data) {
              pubKey = oData.responseMsg.data;
              callback()
            }
          })
        }

        //RSA加密
        function setEncrypt(value) {
          var encrypt = new JSEncrypt();
          encrypt.setPublicKey(pubKey);
          return encrypt.encrypt(value);
        }
      },
      backPaly(data) {
        var cameraIndexCode = data.indexCode;   //获取输入的监控点编号值，必填
        cameraIndexCode = cameraIndexCode.replace(/(^\s*)/g, "");
        cameraIndexCode = cameraIndexCode.replace(/(\s*$)/g, "");

        var startTimeStamp = new Date().getTime() / 1000 - (24 * 3600);
        var endTimeStamp = new Date().getTime() / 1000;

        this.oBacControl.JS_RequestInterface({
          funcName: "startPlayback",
          argument: JSON.stringify({
            cameraIndexCode: cameraIndexCode,                //监控点编号
            startTimeStamp: startTimeStamp,                          //主子码流标识
            endTimeStamp: endTimeStamp,                          //传输协议
            recordLocation: 1,                                   //   1 本地存储   0  中心存储
            transMode: 1, //是否开启GPU硬解
            gpuMode: 0                                     //可指定播放窗口
          })
        })
      },
      initbackWnd() {
        //声明公用变量
        let that = this;
        let initCount = 0;
        let pubKey = '';
        let iWidth = $("#backWnd").width();
        let iHeight = $("#backWnd").height();

        that.oBacControl = new WebControl({ // 创建 WebControl 实例
          szPluginContainer: "backWnd", // 指定 DIV 窗口标识
          iServicePortStart: 15900, // 指定起止端口号，建议使用该值
          iServicePortEnd: 15909,
          // 用于 IE10 使用 ActiveX 的 clsid
          szClassId: "23BF3B0A-2C56-4D97-9C03-0CB103AA8F11",
          cbConnectSuccess: function () {
            // 创建 WebControl 实例成功
            that.oBacControl.JS_StartService("window", {         // WebControl实例创建成功后需要启动服务
              dllPath: "./VideoPluginConnect.dll"         // 值"./VideoPluginConnect.dll"写死
            }).then(function () {                           // 启动插件服务成功
              that.oBacControl.JS_SetWindowControlCallback({   // 设置消息回调
                cbIntegrationCallBack: cbIntegrationCallBack
              });
              that.oBacControl.JS_CreateWnd("backWnd", iWidth, iHeight).then(function () { //JS_CreateWnd创建视频播放窗口，宽高可设定
                init();  // 创建播放实例成功后初始化
              });
            }, function () { // 启动插件服务失败
            });
          },
          cbConnectError: function () {
            // 创建 WebControl 实例失败
            that.isplug = true;
          },
          cbConnectClose: function (bNormalClose) {
            console.log("cbConnectClose");
            that.oBacControl = null;
            // 插件使用过程中发生的断开与插件服务连接的回调
            // bNormalClose = false 时表示异常断开
            // bNormalClose = true 时表示正常断开
          }
        })

        function cbIntegrationCallBack(oData) {
          console.log(JSON.stringify(oData.responseMsg));
        }

        function init() {
          getPubKey(function () {
            ////////////////////////////////// 请自行修改以下变量值	////////////////////////////////////
            var appkey = that.appKey;                //综合安防管理平台提供的appkey，必填
            var secret = setEncrypt(that.appSecret);   //综合安防管理平台提供的secret，必填
            var ip = that.host;                          //综合安防管理平台IP地址，必填
            var playMode = 1;                                  //初始播放模式：0-预览，1-回放
            var port = that.port;                                      //综合安防管理平台端口，若启用HTTPS协议，默认443
            var snapDir = "D:\\SnapDir";                       //抓图存储路径
            var videoDir = "D:\\VideoDir";                     //紧急录像或录像剪辑存储路径
            var layout = "1x1";                                //playMode指定模式的布局
            var enableHTTPS = 1;                               //是否启用HTTPS协议与综合安防管理平台交互，这里总是填1
            var encryptedFields = 'secret';					   //加密字段，默认加密领域为secret
            var showToolbar = 1;                               //是否显示工具栏，0-不显示，非0-显示
            var showSmart = 1;                                 //是否显示智能信息（如配置移动侦测后画面上的线框），0-不显示，非0-显示
            var buttonIDs = "0,16,256,257,258,259,260,512,513,514,515,516,517,768,769";  //自定义工具条按钮
            var toolBarButtonIDs = "2048,2049,2050,2304,2306,2305,2307,2308,2309,4096,4608,4097,4099,4098,4609,4100";
            ////////////////////////////////// 请自行修改以上变量值	////////////////////////////////////


            that.oBacControl.JS_RequestInterface({
              funcName: "init",
              argument: JSON.stringify({
                appkey: appkey,                            //API网关提供的appkey
                secret: secret,                            //API网关提供的secret
                ip: ip,                                    //API网关IP地址
                playMode: playMode,                        //播放模式（决定显示预览还是回放界面）
                port: port,                                //端口
                snapDir: snapDir,                          //抓图存储路径
                videoDir: videoDir,                        //紧急录像或录像剪辑存储路径
                layout: layout,                            //布局
                enableHTTPS: enableHTTPS,                  //是否启用HTTPS协议
                encryptedFields: encryptedFields,          //加密字段
                showToolbar: showToolbar,                  //是否显示工具栏
                showSmart: showSmart,                      //是否显示智能信息
                buttonIDs: buttonIDs,                       //自定义工具条按钮
                toolBarButtonIDs: toolBarButtonIDs
              })
            }).then(function (oData) {
              that.oBacControl.JS_Resize(iWidth, iHeight);  // 初始化后resize一次，规避firefox下首次显示窗口后插件窗口未与DIV窗口重合问题
            });
          });
        }

        function getPubKey(callback) {
          that.oBacControl.JS_RequestInterface({
            funcName: "getRSAPubKey",
            argument: JSON.stringify({
              keyLength: 1024
            })
          }).then(function (oData) {
            console.log(oData);
            if (oData.responseMsg.data) {
              pubKey = oData.responseMsg.data;
              callback()
            }
          })
        }

        //RSA加密
        function setEncrypt(value) {
          var encrypt = new JSEncrypt();
          encrypt.setPublicKey(pubKey);
          return encrypt.encrypt(value);
        }
      },
      // var uploadedDataURL = '/papi/' + this.areaId + '_json/gnqh.json';
      map(url) {
        let vm = this
        let myChart = echarts.getInstanceByDom(document.getElementById("map"))
        if (myChart == null) { // 如果不存在，就进行初始化
          myChart = echarts.init(document.getElementById("map"));
        }
        myChart.clear();
        let uploadedDataURL = '/papi/0000085_json/gnqh.json';
        let tempData1 = [
          {
            name: '执法大队',
            value: [115.5456, 37.5641],
            indexCode: '2404687c5cd841d5b2231e8fab7ad163'
          }
        ];
        let tempData2 = [
          {
            name: '执法大队',
            value: [115.5776, 37.5636],
            indexCode: '39646316074f4b3cb4dc34031461d79f'
          },
        ];
        $.getJSON(uploadedDataURL, function (csJson) {
          echarts.registerMap('songshan', csJson);
          myChart.showLoading('default', {
            text: '加载中，请稍候...', maskColor: 'rgba(0,0,0,.3)', textColor: '#fff',
          });
          let option = {
            geo: {
              map: 'songshan',
              show: false,
              roam: false,
              label: {
                normal: {
                  show: false,
                },
                emphasis: {
                  show: false,
                },
              },
              itemStyle: {
                normal: {
                  areaColor: '#185CA8',
                  borderColor: '#57E1FE',
                  borderWidth: 1,
                },
                emphasis: {},
              },
            },
            series: [
              {
                name: '衡水湖',
                type: 'map',
                mapType: 'songshan',
                label: {
                  normal: {
                    textStyle: {
                      fontSize: 15,
                      fontWeight: 'bold',
                      color: '#fff',
                    },
                  },
                },
                aspectScale: 0.75,
                zoom: 1,
                itemStyle: {
                  normal: {
                    label: {show: true},
                    color: '#F4F4F4',
                    borderWidth: 0.5, //区域边框宽度
                    areaColor: '#185CA8',
                    borderColor: '#57E1FE',
                  },
                  emphasis: {
                    label: {show: false},
                    borderWidth: 0.5,
                    borderColor: '#4b0082',
                    areaColor: '#3B64BA',
                  },
                },
              },
              {
                type: 'scatter',
                coordinateSystem: 'geo',
                symbol: 'image:///static/images/shexiangtou.png',
                legendHoverLink: true,
                symbolSize: [28, 33],
                // legendHoverLink: true,
                itemStyle: {
                  normal: {
                    color: '#D8BC37', //标志颜色
                    shadowBlur: 2,
                    shadowColor: 'D8BC37',
                  },
                },
                data: tempData1,
                showEffectOn: 'render',
                rippleEffect: {
                  brushType: 'stroke',
                },
                hoverAnimation: true,
                zlevel: 1,
              },
              {
                type: 'scatter',
                coordinateSystem: 'geo',
                symbol: 'image:///static/images/shexiangtou.png',
                legendHoverLink: true,
                symbolSize: [28, 33],
                itemStyle: {
                  normal: {
                    color: '#D8BC37', //标志颜色
                    shadowBlur: 2,
                    shadowColor: 'D8BC37',
                  },
                },
                data: tempData2,
                showEffectOn: 'render',
                rippleEffect: {
                  brushType: 'stroke',
                },
                hoverAnimation: true,
                zlevel: 1,
              },
            ],
          };
          setTimeout(function () {
            myChart.hideLoading();
          }, 500);
          myChart.setOption(option, true);
          myChart.on('click', function (param) {
            if (param.seriesType === 'scatter') {
              vm.singlepreview(param.data);
              vm.backPaly(param.data);
            }
          });
          myChart.resize();
          window.addEventListener("resize", function () {
            myChart.resize();
          })
        });
      },
      filteryType(e) {
        if (e == '实验区') {
          return 'rgba(203, 255, 252, 0.8)'
        }
        if (e == '缓冲区') {
          return 'rgba(74, 239, 230, 0.8)'
        }
        if (e == '核心区') {
          return 'rgba(4, 178, 169, 0.8)'
        }
        return 'rgba(203, 255, 252, 0.8)'
      },
    },
    beforeRouteLeave(to, from, next) {
      //oBacControl
      if (this.oWebControl != null) {
        this.oWebControl.JS_HideWnd();   // 先让窗口隐藏，规避可能的插件窗口滞后于浏览器消失问题
        this.oWebControl.JS_Disconnect().then(function () {  // 断开与插件服务连接成功
          },
          function () {  // 断开与插件服务连接失败
          });
      }
      if (this.oBacControl != null) {
        this.oBacControl.JS_HideWnd();   // 先让窗口隐藏，规避可能的插件窗口滞后于浏览器消失问题
        this.oBacControl.JS_Disconnect().then(function () {  // 断开与插件服务连接成功
          },
          function () {  // 断开与插件服务连接失败
          });
      }
      next();
    }
  }
</script>

<style scoped>
  @import "../../static/css/jbxx.css";
  @import "../../static/css/spjk.css";
</style>
